<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 回访管理
 *
 * @icon fa fa-circle-o
 */
class Huifang extends Backend
{

    /**
     * Huifang模型对象
     * @var \app\admin\model\Huifang
     */
    protected $model = null;

    /**
     * 是否开启数据限制
     * 支持auth/personal
     * 表示按权限判断/仅限个人
     * 默认为禁用,若启用请务必保证表中存在admin_id字段
     */
    protected $dataLimit = true;

    /**
     * 数据限制字段
     */
    protected $dataLimitField = 'admin_id';

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['getAdminNickname'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Huifang;
        $this->view->assign("sexList", $this->model->getSexList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 判断权限,如果是管理员以上权限,直接跳转到 控制台
     */
    protected function toDashboard()
    {
        /*
         * group_id > 3 作为判断条件,就是导医以上权限,这些权限直接跳转到 控制台页面
         */
        $authList = $this->auth->getGroups();
        if ($authList[0]['group_id'] < 3) {
            //$this->success("", "./dashboard");
        }


    }

    /**
     * 查看
     */
    public function index()
    {
        //加一条跳转条件,如果是导医以上权限,直接跳转到 控制台页面
        $this->toDashboard();

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);


        //获取导医的名称并赋给前端 供搜索用
        $adminNicknameList = $this->getAdminNickname();
        $this->assign('adminNicknameList', $adminNicknameList);


        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['admin'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('admin')->visible(['id', 'nickname']);
            }

            //导医那一项目是否显示,根据权限分配
            /**
             * 一般来说,如果显示导医的选择项,说明是管理员,所以以此,来判断是否是管理员
             * 今天需要回访人数和明日回访的人数,需要判断权限
             * 如果是 管理员 则看到所有, 如果是 导医, 则只看到自己的
             */
            if ($this->auth->check('huifang/showNickname')) {
                $showNickname = 1;
                //今天需要回访人数 $today_num
                $today_num = $this->model->whereTime('hftime', 'between', getDateString())->count();
                //明天需要回访人数 $tomorrow_num
                $tomorrow_num = $this->model->whereTime('hftime', 'between', getDateString(1))->count();
            } else {
                $showNickname = 0;

                //今天需要回访人数 $today_num
                $today_num = $this->model
                    ->where('admin_id', $this->auth->id)
                    ->whereTime('hftime', 'between', getDateString())->count();
                //明天需要回访人数 $tomorrow_num
                $tomorrow_num = $this->model
                    ->where('admin_id', $this->auth->id)
                    ->whereTime('hftime', 'between', getDateString(1))->count();
            }


            $result = array("total" => $list->total(), "rows" => $list->items(), "extend" => ['today_num' => $today_num, 'tomorrow_num' => $tomorrow_num, 'showNickname' => $showNickname]);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 回访测试
     */
    public function test()
    {
        //dump($this->getDataLimitAdminIds());
        //dump($this->auth->getGroups());
        //dump("---");
        //dump($this->auth->getRuleList());

        //dump($this->auth->check('huifang/del'));

        /*
        $adminList = Db::name('admin')
            ->alias('a')
            ->join('fa_auth_group_access b', 'a.id = b.uid')
            ->select();
        */

        //dump($adminList);

        //dump($this->auth);
        //echo($this->auth->id);


    }




    /**
     * 显示导医那一项
     *
     * @remark 用来操作是否显示导医项目. 导医自己登陆,则不显示,如果是上级登陆则显示.
     */
    public function showNickname()
    {
    }

    /**
     * @remark 获取 admin表的 nickname字段, 供选项下拉用.
     */
    protected function getAdminNickname()
    {

        $admin = new Admin();
        /*
         * 通过查询 fa_auth_group_access表,group_id == 3的就是 客服权限
         * fa_auth_group_access表 和 admin表连表
         */

        $adminList = $admin
            ->alias('a')
            ->join('fa_auth_group_access b', 'a.id = b.uid')
            ->field('id,nickname,group_id')
            ->select();

        $adminData = [];
        foreach ($adminList as $k => $v) {
            if ($v['group_id'] == '3') {
                array_push($adminData, $v['nickname']);
            }
        }
        return $adminData;
    }

    /**
     * 回访记录
     */
    public function huifangjilu($ids)
    {
        // 指定 model
        $fuzhenModel = new \app\admin\model\Fuzhen();
        // 查询数据
        $fuzhenArray = $fuzhenModel->where('huifang_id', $ids)
            ->order('createtime', 'desc')
            ->select();

        if ($this->request->isAjax()) {
            $this->success();
        }

        $this->assign('fuzhenArray', $fuzhenArray);
        return $this->view->fetch();
    }

    /**
     * 增加回访记录
     */
    public function huifangadd($ids = 0)
    {
        // 指定 model
        $fuzhenModel = new \app\admin\model\Fuzhen();
        // 把当前的id获取到给页面中
        $this->assign("ids", $ids);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $fuzhenModel->validateFailException(true)->validate($validate);
                    }
                    $result = $fuzhenModel->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

}
